import { useEffect, useState } from 'react';
import { init, dispose } from 'klinecharts';
import { klineApi } from '@/api';
import styles from '../index.module.less';
import useScreenSize from '@/hooks/useScreenSize';
import useRoute from '@/hooks/useRoute';
import { pageLeftWidthAtom } from '@/stores';
import { useAtomValue } from 'jotai';

let chart: any;
const initWidth = 884;
export default function KLine({}: any) {
  const [isfirst, setIsfirst] = useState<boolean>(true);
  const [list, setList] = useState<any[]>([]);
  const [width, setWidth] = useState<number>(initWidth);
  const screenWidth = useScreenSize().width;
  const { getPageParams } = useRoute();
  const curContract = getPageParams('contract');
  const pageLeftWidth = useAtomValue(pageLeftWidthAtom);

  useEffect(() => {
    initKline();
    getKline();
  }, []);

  useEffect(() => {
    if (list.length > 0) chart.applyNewData(list);
  }, [list]);

  useEffect(() => {
    setLineWidth();
  }, [pageLeftWidth]);

  function setLineWidth() {
    let _width = screenWidth < 1200 ? initWidth : pageLeftWidth - 280;
    setWidth(_width);
    setTimeout(() => {
      // chart.resize();
    }, 100);
  }

  // useEffect(() => {
  //   setLineWidth();
  // }, [screenWidth]);

  // 初始化k线图
  function initKline() {
    // console.log('初始化k线图');
    if (chart) chart = null;
    chart = init('chart', {
      layout: [
        {
          type: 'candle',
          content: ['MA', { name: 'EMA', calcParams: [10, 30] }],
          options: { order: Number.MIN_SAFE_INTEGER },
        },
        { type: 'indicator', content: ['VOL'], options: { order: 10 } },
        { type: 'xAxis', options: { order: 9 } },
      ],
    });
    return () => {
      dispose('chart');
    };
  }

  // k线图
  async function getKline() {
    const params = {
      contract: curContract,
      interval: '15m',
      price_type: 'last',
      limit: 1000,
    };
    const val: any = (await klineApi(params))?.data;
    // console.log('res-k线图: ', val);
    const res = val?.map((item: any) => {
      const obj = {
        timestamp: item?.t * 1000,
        open: item?.o,
        high: item?.h,
        low: item?.l,
        close: item?.c,
        volume: '',
      };
      return obj;
    });
    // console.log('res-k线图1: ', res[0]);
    setList(res);
  }

  return (
    <div className={`${styles.klineWrap} zcard`} style={{ width: `${width}px` }}>
      <div style={{ width: `${width}px` }}></div>
      <div id="chart" style={{ width: `${width}px`, height: 548, background: '#fff' }} />
    </div>
  );
}
